package com.fq.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MybatisUtil {
    private static SqlSessionFactory factory;

    private static ThreadLocal<SqlSession> t=new ThreadLocal<>();
    static {
        try {
            factory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static SqlSession getSqlSession(boolean autoccmmit){
        SqlSession sqlSession=t.get();
        if (sqlSession==null){
            sqlSession=factory.openSession(autoccmmit);
            t.set(sqlSession);
        }
        return sqlSession;
    }
    public static SqlSession getSqlSession(){

        return getSqlSession(false);
    }

    public static <T> T getMapper(Class<T> c){
        SqlSession session=getSqlSession(true);
        T tt=session.getMapper(c);
        t.remove();
        return tt;
    }


    public static void commit(){
        SqlSession session=getSqlSession();
        session.commit();
        t.remove();
    }

    public static void rollback(){
        SqlSession session=getSqlSession();
        session.rollback();
        t.remove();
    }

}
